﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;
using System.IO;

namespace V5_EaspLibs.Utility {
    /// <summary>
    /// 抽象工厂模式创建DAL。
    /// web.config 需要加入配置：(利用工厂模式+反射机制+缓存机制,实现动态创建不同的数据层对象接口)  
    /// DataCache类在导出代码的文件夹里
    /// <appSettings>  
    /// <add key="DAL" value="Maticsoft.SQLServerDAL" /> (这里的命名空间根据实际情况更改为自己项目的命名空间)
    /// </appSettings> 
    /// </summary>
    public sealed class DataAccess {
        public static readonly string AssemblyPath = ConfigurationManager.AppSettings["dbType"];
        /// <summary>
        /// 创建对象或从缓存获取
        /// </summary>
        public static object CreateObject(string AssemblyPath, string ClassNamespace) {
            object objType = Easp.Cache.GetCache(ClassNamespace);//从缓存读取
            if (objType == null) {
                try {
                    objType = Assembly.Load(AssemblyPath).CreateInstance(ClassNamespace);//反射创建
                    Easp.Cache.SetCache(ClassNamespace, objType);// 写入缓存
                }
                catch { }
            }
            return objType;
        }

        /// <summary>
        /// 创建接口
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public static object IDALObject(string className) {
            string BaseNameSpace = "V5_DAL";
            string ClassNamespace = BaseNameSpace + "." + AssemblyPath + "." + className;
            object objType = IDALObject("V5_DAL." + AssemblyPath, ClassNamespace);
            return objType;
        }

        /// <summary>
        /// 创建接口
        /// </summary>
        /// <param name="BaseNameSpace"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        public static object IDALObject(string BaseNameSpace, string className) {
            object objType = CreateObject(BaseNameSpace, className);
            return objType;
        }
        /// <summary>
        /// 创建接口
        /// </summary>
        /// <param name="BaseDLL"></param>
        /// <param name="BaseNameSpace"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        public static object IDALObject(string BaseDLL, string BaseNameSpace, string className) {
            object objType = CreateObject(BaseDLL, BaseNameSpace + "." + AssemblyPath + "." + className);
            return objType;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="defaultValue">V5_CMS</param>
        /// <param name="newValue">V5_DAL</param>
        /// <returns></returns>
        public static string GetDALDLLName(string defaultValue, string newValue) {
            if (!File.Exists(newValue + "." + AssemblyPath + ".dll")) {
                return defaultValue;
            }
            return newValue;
        }
    }
}
